import { createRouter, RouteRecordRaw,createWebHashHistory } from 'vue-router'
import store from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/layout',
    name: 'Layout',
    component: ()=>import('@/layout/Layout.vue'),
    children: [
      {
        path: 'content',
        name: 'Content',
        component: ()=>import('@/views/Content.vue'),
      },
      {
        path: 'userAdmin',
        name: 'UserAdmin',
        component: () => import('../views/admin/UserAdmin.vue')
      },
      {
        path: '/layout',
        redirect: '/layout/content'
      }
    ],
 
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import( '../views/Login.vue'),
    meta: {
      // 不需要路由管理
      require: false
    }
  },

  {
    path: '/',
    redirect: '/layout/content'
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})
// 使用全局路由守卫
// router.replace('/login'); // 如果没有登录，那么就跳转到登录页
router.beforeEach((to, from, next) => {
  console.log('to----',to);
  console.log('from------',from);
  // 登录页面不需要进行路由管理
  if(to.meta.require !== false){
    const token = store.state.user.token;
    if(token){ // token存在，那么表示可以放行
      next()
    }else {
      // 否则就表示没有登录，那么跳回登录页
      next('/login')
    }
    next();
  }
  next()
  //#region 
  // if (to.matched.some(function (item) {
  //   console.log(item, "是否需要登录校验：", item.meta.require);
  //   return item.meta.require;
  // })) {
  //   const token = store.state.user.token;
  //   if(!token){
  //     next('/login');
  //   }else {
  //     next();
  //   }
  // } else {
  //   next();
  // }
  //#endregion
})
export default router
